<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇我们将基础性的学习Object的定义、成员的访问，然后了解对象与引用类型，构造函数与类的区别，最后再补充说明对象的继承方式。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：Object">
<meta property="og:url" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇我们将基础性的学习Object的定义、成员的访问，然后了解对象与引用类型，构造函数与类的区别，最后再补充说明对象的继承方式。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/javascript.jpg">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/proto.png">
<meta property="og:updated_time" content="2019-05-15T12:39:20.523Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：Object">
<meta name="twitter:description" content="本篇我们将基础性的学习Object的定义、成员的访问，然后了解对象与引用类型，构造函数与类的区别，最后再补充说明对象的继承方式。">
<meta name="twitter:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/">





  <title>《JavaScript 高级程序设计》第五章：Object | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Object/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：Object</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-01T07:01:16+08:00">
                2019-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/04/01/professional-javascript-chapter-5-Object/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇我们将基础性的学习Object的定义、成员的访问，然后了解对象与引用类型，构造函数与类的区别，最后再补充说明对象的继承方式。</blockquote>

<a id="more"></a>
<h2 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h2><h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>按照 ECMA-262 定义，“对象”是无序属性的集合。每条属性都是由 <code>key : value</code> 构成的“键值对”，其中 <code>key</code> 称之为“属性名”，<code>value</code> 则是属性名对应的“值”。“属性值” 可以是任何数据类型，包括基本值、对象、函数等。需要注意的是如果当 <code>value</code> 是一个方法或函数时，我们通常又称 <code>key</code> 为方法名。</p>
<h3 id="成员组成"><a href="#成员组成" class="headerlink" title="成员组成"></a>成员组成</h3><p>“对象” 是无序属性的集合，同理 “对象” 也是一系列无序键值对的集合，更是囊括不同类型数据和方法的集合体。因此对象中的每条 <code>key/value</code> 都可以看做成是这个对象的组成“成员”，而 <code>key</code> 则是对象的属性名或方法名，<code>value</code> 则是对象的属性值或功能方法。</p>
<p>在 ECMAScript 中 <code>key</code> 的名称可以由任何属于 <code>Unicode</code> 编码的字符组成，但常用的还是数字与字母。</p>
<h3 id="成员访问"><a href="#成员访问" class="headerlink" title="成员访问"></a>成员访问</h3><p>在 ECMAScript 中成员的访问主要有两种方式：</p>
<ul>
<li>“点” 表示法</li>
<li>“[]” 方括号表示法</li>
</ul>
<p>它们的区别是 “点” 表示法更通用，更直观，更快捷。但缺点则是无法访问含有特殊字符、关键字、保留字的成员名。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Person.first name <span class="comment">// Syntax Error</span></span><br></pre></td></tr></table></figure>
<p>此时，括号表示法的强大就体现了出来。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Person [<span class="string">'first name'</span>];</span><br><span class="line">Person [<span class="string">'first'</span> + <span class="string">'name'</span>];</span><br></pre></td></tr></table></figure>
<h2 id="引用类型与对象"><a href="#引用类型与对象" class="headerlink" title="引用类型与对象"></a>引用类型与对象</h2><p>ECMAScript 中有两种数据类型：“基本数据类型” 与 “引用数据类型”，</p>
<p>数据类型，顾名思义就是对数据进行分类，像 <code>number、Number、string、String、boolean、Boolean、null、undefined、Object、Function、RegExp、Date、Array、Error</code> 等都可以看做成是 ECMAScript 中的数据，如果对它们进行分类，从变量的角度去看非常好理解，如果把 <code>number、string、boolean、null、undefined</code> 赋值给某个变量，那么变量中保存的就是这些数据的本身（实际值），属于 “按值访问”，这种数据我们就称之为 “基本数据类型”，而 <code>Object</code> 是一个对象，当它被赋值给某个变量时，变量中保存的并非是这个对象本身，而是对象的引用（指针），此时属于 “引用访问”，所以像这种数据类型，我们称之为 “引用类型”。</p>
<p>在 JavaScript 中一切皆为对象，像 <code>RegExp Function Date Error Array String Number Boolean</code> 等都是继承于 <code>Object</code>，所以它们也是对象，因此 <code>Object</code> 在 JavaScript 中是一切对象的基础对象。更直白的说上述的所有对象因为在原型链上都继承着 <code>Object</code>，所以可以看作是对 <code>Object</code> 的扩展对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Location.__proto__.__proto__</span><br><span class="line"><span class="built_in">Array</span>.__proto__.__proto__</span><br><span class="line"><span class="built_in">JSON</span>.__proto__</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">&#123;</span></span><br><span class="line"><span class="comment">    constructor : ƒ Object()</span></span><br><span class="line"><span class="comment">    hasOwnProperty:ƒ hasOwnProperty()</span></span><br><span class="line"><span class="comment">    isPrototypeOf:ƒ isPrototypeOf()</span></span><br><span class="line"><span class="comment">    propertyIsEnumerable:ƒ propertyIsEnumerable()</span></span><br><span class="line"><span class="comment">    toLocaleString:ƒ toLocaleString()</span></span><br><span class="line"><span class="comment">    toString:ƒ toString()</span></span><br><span class="line"><span class="comment">    valueOf:ƒ valueOf()</span></span><br><span class="line"><span class="comment">    get __proto__:ƒ __proto__()</span></span><br><span class="line"><span class="comment">    set __proto__:ƒ __proto__()  </span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>既然 <code>RegExp、Function、Date、Error、Array、String、Number、Boolean</code> 等都是对象，所以它们也属于 “引用类型”，而 “引用类型” 的值就是其对象实例。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>();</span><br></pre></td></tr></table></figure>
<p>其中变量 <code>obj、arr、str</code> 等都是“引用类型”，它们的值分别是构造函数 <code>Object</code> 的实例(对象实例)、<code>Array</code> 的实例(数组实例对象)、<code>String</code> 的实例(字符串实例对象)。实例会继承着对应引用类型的属性和方法，关于继承的详细机制则下面会说到。</p>
<p>《JavaScript 高级程序设计》中提到 <code>“引用类型” 是一种数据结构，它将数据（属性）与功能（方法）组织在一起。</code> 其本质还是因为 “引用类型” 值(对象)的特性。虽然在 ECMAScript 中 <code>Object</code> 的实例并不具备多少功能，但是利用实例对象的结构特征，对于应用程序中数据的存储与传输而言，则是非常理想的选择。</p>
<p>个人看来，“引用类型” 是将“对象”数据化的看待角度，所以“引用类型” 必然是对象，但是对象不一定就是“引用数据类型”，因此 Location、XMLHttpRequest、Window、JSON 等虽然也是对象，但并不是一种“引用数据类型”。而“构造函数”又是产生对象的工厂，所以构造函数便可以认为是对“引用类型”更具体的表示，或者说构造函数本身便表示了对象是何种引用类型，例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>() <span class="keyword">instanceof</span> <span class="built_in">Array</span>;           <span class="comment">//true 说明引用类型中的数组类型</span></span><br><span class="line"><span class="built_in">Object</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;         <span class="comment">//true 说明引用类型中的对象类型</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">String</span>() <span class="keyword">instanceof</span> <span class="built_in">String</span>;     <span class="comment">//true 说明引用类型中的字符串类型</span></span><br></pre></td></tr></table></figure>
<p>又因为 JavaScript 中 <code>Object</code> 是一切对象的基础，所以下面的条件也会成立：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Boolean</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;    <span class="comment">//true</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Number</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;     <span class="comment">//true</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;       <span class="comment">//true</span></span><br><span class="line"><span class="built_in">RegExp</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;         <span class="comment">//true</span></span><br><span class="line"><span class="built_in">Function</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;       <span class="comment">//true</span></span><br><span class="line"><span class="built_in">Error</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;          <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>等后面我们详细学习每个构造函数的时候，我们还会发现有些引用类型的“构造函数”既是“构造函数”也可以充当普通的函数来使用，其实通过上面的两个示例我们就能发现一些端倪：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">String</span>() <span class="keyword">instanceof</span> <span class="built_in">String</span>;     <span class="comment">//true</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Boolean</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;    <span class="comment">//true</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Number</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;     <span class="comment">//true</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;       <span class="comment">//true</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">String</span>() <span class="keyword">instanceof</span> <span class="built_in">String</span>;         <span class="comment">//false</span></span><br><span class="line"><span class="built_in">Boolean</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;        <span class="comment">//false</span></span><br><span class="line"><span class="built_in">Number</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;         <span class="comment">//false</span></span><br><span class="line"><span class="built_in">Date</span>() <span class="keyword">instanceof</span> <span class="built_in">Object</span>;           <span class="comment">//false</span></span><br></pre></td></tr></table></figure>
<p>最后，在第六章我们会讲通过自定义构造函数来创建自定义的“引用类型”。</p>
<blockquote>
<p>关于 “基本数据类型” 详解，请见 <code>第三章 - 数据类型 - 基本数据类型</code></p>
</blockquote>
<h2 id="类与构造函数"><a href="#类与构造函数" class="headerlink" title="类与构造函数"></a>类与构造函数</h2><p>“类”在面向对象编程语言中，可以很方便快速的创建具有相同属性与方法的对象(实例)，但是 JavaScript 中虽然也有面向对象的概念，但是对象的“继承”是基于原型、原型链的机制，因此严格的来说，JavaScript 是一门“基于原型的面向对象的脚本语言”，而与“类”具有相似的产物便是“构造函数”，但与 Java 这样面向对象语言中的“类”，还是有很大的区别，简要可以概括出三点：</p>
<h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><p>Java中的对象必须由“类”来实例化，而 JavaScript 中对象可以由字面量格式非常简单的定义与创建，在 JavaScript 中对象就是很单纯的数据与功能的集合。</p>
<h3 id="调用"><a href="#调用" class="headerlink" title="调用"></a>调用</h3><p>Java 中类是不可以直接调用的，只是用来实例化对象，就算是调用方法也只能调用类上的静态方法，而在 JavaScript 中 充当类的构造函数是可以作为函数来调用的，例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>(); <span class="comment">//&#123;&#125;</span></span><br><span class="line"><span class="built_in">String</span>(); <span class="comment">//""</span></span><br><span class="line"><span class="built_in">Number</span>(); <span class="comment">//0</span></span><br></pre></td></tr></table></figure>
<p>另外构造器方法上的静态方法也可以直接使用，例如：<code>String.fromCharCode(65)</code>。因此可以看出 JS 对函数式编程支持更好！</p>
<h3 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h3><p>在面向对象编程语言中 “类” 的重要概念就是继承，由“类”实例化的对象便会继承该类的方法与属性，这种继承关系更类似于派生以及父子关系，而在 JS 中继承被更多的看作成具有相互关联的关系，而这个关系的联接就是我们常说的“原型链(<strong>proto</strong>)”。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Behavior = &#123;</span><br><span class="line">    eat: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        alert(<span class="string">'eat'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> Tom = &#123; <span class="attr">name</span>: <span class="string">'my name is Tom'</span>, <span class="attr">__proto__</span>: Behavior &#125;;</span><br><span class="line"><span class="keyword">var</span> Bob = &#123; <span class="attr">name</span>: <span class="string">'my name is Bob'</span>, <span class="attr">__proto__</span>: Behavior &#125;;</span><br><span class="line"></span><br><span class="line">Tom.name; <span class="comment">// my name is Tom;</span></span><br><span class="line">Tom.eat();</span><br><span class="line">Bob.eat();</span><br></pre></td></tr></table></figure>
<p>当然 JS 也支持面向对象开发语言的 <code>new</code> 运算符，例如常见的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br></pre></td></tr></table></figure>
<p>但实际上这个 <code>new</code> 运算符更多的充当着语法糖角色，大致上来说，<code>new</code> 运算符主要有以下功能：</p>
<ul>
<li>新建并返回一个构造器函数的实例对象，<code>Constructor {}</code> ，然后将构造函数中的 <code>this</code> 对象复制到新建的实例对象 <code>this</code> 上。</li>
<li>把构造函数的 <code>prototype</code> 对象复制到新建对象的 <code>__proto__</code> 属性上，以便继承该构造器 <code>prototype</code> 对象上的属性与方法，例如：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">obj.__proto__ === <span class="built_in">Object</span>.prototype; <span class="comment">// true;</span></span><br></pre></td></tr></table></figure>
<p>实例化得到的 obj 对象其 <code>__proto__</code> 属性所指向关联（继承）的就是 <code>Object()</code> 构造器的 <code>prototype</code> 属性（原型属性）。<br>再比如一个完整的例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Student</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Student.prototype.say = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="comment">//将实例对象的 __proto__ 与自身的 prototype 进行了关联。</span></span><br><span class="line">    alert(<span class="keyword">this</span>.name); <span class="comment">//复制了this到实例对象上</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> Tom = <span class="keyword">new</span> Student(<span class="string">'Tom'</span>);</span><br><span class="line"></span><br><span class="line">Tom.say(); <span class="comment">//Tome</span></span><br></pre></td></tr></table></figure>
<p>此时 <code>new</code> 运算符做了两件事，第一把 <code>Student</code> 中的 <code>this</code> 复制到新的实例对象 Tom 上所以 Tom 上也存在 <code>name</code> 属性，并且值就是实例化过程中传入的 <code>Tom</code>。第二则是把 <code>Student</code> 的 <code>prorotype</code> 对象复制到 Tom 这个实例化对象的 <code>__proto__</code> 属性上。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(Student.prototype);</span><br><span class="line"><span class="built_in">console</span>.log(Tom.__proto__);</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">&#123;</span></span><br><span class="line"><span class="comment">    say: ƒ()</span></span><br><span class="line"><span class="comment">    constructor: ƒ Student(name)</span></span><br><span class="line"><span class="comment">    __proto__: Object</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>从上例可以看出 <code>Tom.__proto__</code> 与 <code>Student.prototype</code> 指向的都是同一个原型对象，所以就非常好理解通过 <code>new</code> 运算符是如何实现继承关系的了。<br>下面是该原型对象上的具体属性与方法：</p>
<ul>
<li>say ： 原型对象上的方法，可以被其实例对象继承。</li>
<li>constructor : 用于说明当前的原型对象属于那个构造函数，同时也是为了实现一个闭环的循环访问（构造函数通过 <code>prototype</code> 访问原型对象，原型对象再通过 <code>constructor</code> 属性访问所依附的构造函数 ）。</li>
<li><strong>proto</strong> : 该原型对象(prototype)上的原型链属性（用于说明该原型对象自身的继承关系）。</li>
</ul>
<p>一般来说实例对象的 <code>__proto__</code> 属性保存的是其构造函数的 <code>prototype</code> 原型对象，而构造函数的原型对象本身也通过 <code>__proto__</code> 来说明其自身的继承关系，同样的，原型对象的继承对象也含有 <code>__proto__</code> 属性，依次类推我们便可以得出一个 <code>__proto__</code> 属性串联出的 “继承链—&gt;原型链”。</p>
<p>以一个实例的数组对象为例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>()</span><br><span class="line">    length: <span class="number">0</span></span><br><span class="line">    __proto__: <span class="built_in">Array</span>(<span class="number">0</span>)&#123;</span><br><span class="line">        </span><br><span class="line">        map:ƒ map()</span><br><span class="line">        filter:ƒ filter()</span><br><span class="line">        push:ƒ push()</span><br><span class="line">        indexOf:ƒ indexOf()</span><br><span class="line">        sort:ƒ sort()</span><br><span class="line">        ...</span><br><span class="line">        <span class="keyword">constructor</span>:ƒ Array()</span><br><span class="line">            __proto__:Object&#123;</span><br><span class="line">                <span class="keyword">constructor</span>:ƒ Object()</span><br><span class="line">                hasOwnProperty:ƒ hasOwnProperty()</span><br><span class="line">                isPrototypeOf:ƒ isPrototypeOf()</span><br><span class="line">                ...</span><br><span class="line">                __proto__ : null</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>从中我们可以看出 JavaScript Object 对象是一切其它对象的最底层最基础的对象，其它对象都是继承自 Object，而 Object 继承的则是 null。<br>从示例中 <code>Array()</code> 方法产生的匿名实例数组，其 <code>__proto__</code> 属性指向的是 <code>Array</code> 构造函数的 <code>prototype</code> 对象，而 <code>Array</code> 构造函数的 <code>prototype</code> 对象又继承自 <code>Object()</code> 构造函数的 <code>prototype</code> 原型对象。所以这种链式的继承关系可以如下图所示：</p>
<p><img src="/2019/04/01/professional-javascript-chapter-5-Object/proto.png" alt=""></p>
<p>目前我们可以简单的总结下：在 JS 中构造函数类似与面向对象中“类”的关键点就在于方法（函数）具有 <code>prototype</code> 原型对象，它可以作为一个方法与属性的公共载体，用于该构造函数的实例对象通过 <code>__proto__</code> 属性进行继承，并且其本身也通过一个 <code>constructor</code> 属性再循环访问到自身所依附的构造函数。由于普通对象不存在 <code>prototype</code> 对象，所以也就无法充当“类”的角色，但是对象自身 <code>__proto__</code> 属性天生就是用来主动继承的，所以通过手动修改对象的 <code>__proto__</code> 属性也可以很灵活的调整对象与对象之间的继承关系。</p>
<h2 id="实例方法-属性"><a href="#实例方法-属性" class="headerlink" title="实例方法 / 属性"></a>实例方法 / 属性</h2><p><code>实例方法 / 属性</code> 指的是对象实例自身具有的属性或方法，这些属性方法不仅仅是实例自身拥有的，也包括通过 <code>__proto__</code> 原型属性从其构造函数 <code>prototype</code> 上继承而来的。</p>
<p><strong>constructor</strong></p>
<p>保存着创建当前实例对象的构造函数。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Object</span>().constructor; <span class="comment">// "ƒ Object() &#123; [native code] &#125;"</span></span><br></pre></td></tr></table></figure></p>
<p>这说明当前对象的构造函数就是 Object()。</p>
<p><strong>hasOwnProperty()</strong><br>接收一个参数 <code>key</code> ，判断这个成员是否为实例对象私有的方法与属性，而非继承着原型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Test</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">Test.prototype.custom = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> test = <span class="keyword">new</span> Test();</span><br><span class="line"></span><br><span class="line">test.custom_private = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(test.hasOwnProperty(<span class="string">'custom'</span>)); <span class="comment">// false;</span></span><br><span class="line"><span class="built_in">console</span>.log(test.hasOwnProperty(<span class="string">'custom_private'</span>)); <span class="comment">// true;</span></span><br></pre></td></tr></table></figure>
<p><strong>isPrototypeOf()</strong><br>接收一个对象作为参数，判断这个对象是否继承于指定的原型对象。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Test.prototype.isPrototypeOf(test) <span class="comment">// true</span></span><br></pre></td></tr></table></figure></p>
<p><strong>propertyIsEnumerable()</strong><br>接收一个参数 <code>key</code>，判断这个成员在指定的对象上是否可枚举（遍历访问）。<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(test.propertyIsEnumerable(<span class="string">'custom'</span>)); <span class="comment">// false;</span></span><br><span class="line"><span class="built_in">console</span>.log(test.propertyIsEnumerable(<span class="string">'custom_private'</span>)); <span class="comment">// true;</span></span><br></pre></td></tr></table></figure></p>
<p><strong>toLocaleString()</strong><br>把对象转换为符合本地区格式的字符串。</p>
<p><strong>toString()</strong><br>把对象转换为字符串。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">test.toString(); <span class="comment">//  "[object Object]"</span></span><br></pre></td></tr></table></figure>
<p>在 JavaScript 中也只有 Object 的 <code>toString()</code> 方法才会返回这种格式，因此利用这个特性，我们可以在转换格式统一的基础上进行类型的判断。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.prototype.toString.call(&#123;&#125;)      <span class="comment">//"[object Object]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call([])      <span class="comment">//"[object Array]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(<span class="string">""</span>)      <span class="comment">//"[object String]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(<span class="number">1</span>)       <span class="comment">//"[object Number]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(<span class="literal">true</span>)    <span class="comment">//"[object Boolean]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(<span class="literal">null</span>)    <span class="comment">//"[object Null]"</span></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(<span class="literal">undefined</span>)<span class="comment">//"[object Object]"</span></span><br></pre></td></tr></table></figure>
<p><strong>valueOf()</strong><br>返回对象自身。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/14/xss/" rel="next" title="WEB安全 - 认识与防御XSS攻击">
                <i class="fa fa-chevron-left"></i> WEB安全 - 认识与防御XSS攻击
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/01/professional-javascript-chapter-5-Array/" rel="prev" title="《JavaScript 高级程序设计》第五章：Array">
                《JavaScript 高级程序设计》第五章：Array <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#对象"><span class="nav-number">1.</span> <span class="nav-text">对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">1.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#成员组成"><span class="nav-number">1.2.</span> <span class="nav-text">成员组成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#成员访问"><span class="nav-number">1.3.</span> <span class="nav-text">成员访问</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#引用类型与对象"><span class="nav-number">2.</span> <span class="nav-text">引用类型与对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类与构造函数"><span class="nav-number">3.</span> <span class="nav-text">类与构造函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建"><span class="nav-number">3.1.</span> <span class="nav-text">创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调用"><span class="nav-number">3.2.</span> <span class="nav-text">调用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#继承"><span class="nav-number">3.3.</span> <span class="nav-text">继承</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例方法-属性"><span class="nav-number">4.</span> <span class="nav-text">实例方法 / 属性</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
